import React, { useEffect, useState } from "react";
import { Button, Table, message, Popconfirm, Select, Modal } from "antd";
import {
  createWarehouseProduct,
  deleteWarehouseProduct,
  listWarehouseProducts,
  listWarehouses,
  updateWarehouseProduct,
} from "../../api/ckgl";
import WarehouseProductModal from "./componets/WarehouseProductModal";
import RemindTag from "../../components/RemindTag";
const { Option } = Select;

const ListWarehouseProducts = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [warehouseProductList, setWarehouseProductList] = useState<any[]>([]);
  const [totalWarehouseProducts, setTotalWarehouseProducts] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(20);
  const [isWarehouseProductModalVisible, setIsWarehouseProductModalVisible] =
    useState(false);
  const [currentWarehouseProduct, setCurrentWarehouseProduct] =
    useState<any>(null);
  const [warehouses, setWarehouses] = useState<any[]>([]);
  const [warehouseId, setWarehouseId] = useState<number | undefined>(undefined);
  const [count, setCount] = useState<number>(0);
  const [hintText, setHintText] = useState<string | undefined>(undefined);

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "物品名称",
      dataIndex: "product_name",
      key: "product_name",
      render: (text: string) => <span>{text}</span>,
    },

    {
      title: "仓库名称",
      dataIndex: "warehouse_name",
      key: "warehouse_name",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "库存",
      dataIndex: "inventory",
      key: "inventory",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "提醒阈值",
      dataIndex: "reminder_threshold",
      key: "reminder_threshold",
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "是否提醒",
      dataIndex: "remind",
      key: "remind",
      render: (_: any, record: any) => <RemindTag remind={record.remind} />,
    },
    {
      title: "操作",
      dataIndex: "id",
      key: "id",
      render: (_: any, record: any) => (
        <>
          <Button
            type="link"
            onClick={() => handleEditWarehouseProduct(record)}
          >
            编辑
          </Button>
          <Popconfirm
            okText="确定"
            cancelText="取消"
            title="确定删除仓库物品"
            onConfirm={() => handleDeleteWarehouseProduct(record)}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  const handleDeleteWarehouseProduct = (record: any) => {
    deleteWarehouseProduct({
      warehouse_product_id: record.id,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      message.success(
        `仓库物品 "${record.warehouse_name}-${record.product_name}" 删除成功`
      );
      // 更新当前页
      reset(currentPage);
    });
  };

  const handleEditWarehouseProduct = (record: any) => {
    setCurrentWarehouseProduct(record);
    setIsWarehouseProductModalVisible(true);
  };

  const getListWarehouseProducts = (page: number) => {
    // 调用 listWarehouseProducts API，并处理响应
    listWarehouseProducts({
      page,
      size: pageSize,
      warehouse_id: warehouseId,
    })
      .then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        const { warehouse_products, total } = res.data;
        setWarehouseProductList(warehouse_products);
        setTotalWarehouseProducts(total);
      })
      // .catch(() => {
      //   // 用于演示目的，使用模拟数据
      //   const mockWarehouseProducts = [
      //     {
      //       id: 1,
      //       product_id: 1,
      //       warehouse_id: 1,
      //       inventory: 100,
      //       reminder_threshold: 10,
      //       remind: true,
      //       warehouse_name: "wefw",
      //       product_name: "wefwffwe",
      //     },
      //     {
      //       id: 2,
      //       product_id: 2,
      //       warehouse_id: 2,
      //       inventory: 50,
      //       reminder_threshold: 5,
      //       remind: false,
      //       warehouse_name: "wefwwefwe",
      //       product_name: "wefwffwe",
      //     },
      //     // 添加更多的模拟仓库商品
      //   ];

      //   setWarehouseProductList(mockWarehouseProducts);
      //   setTotalWarehouseProducts(mockWarehouseProducts.length);
      // });
  };

  const reset = (page: number) => {
    getListWarehouseProducts(page);
  };

  const handleWarehouseProductModalOk = async (values: any) => {
    // 根据情况调用 createWarehouseProduct 或 updateWarehouseProduct API，并处理响应
    if (currentWarehouseProduct) {
      // 更新
      let msg = "更新成功";
      await updateWarehouseProduct({
        warehouse_product_id: currentWarehouseProduct.id,
        ...values,
      }).then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        message.success(msg);
      });
    } else {
      // 添加
      let msg = "添加成功";
      await createWarehouseProduct({
        ...values,
      }).then((res: any) => {
        if (res?.code !== 0) {
          message.error(res.msg);
          return;
        }
        message.success(msg);
      });
    }
    reset(currentPage);
    setIsWarehouseProductModalVisible(false);
  };

  useEffect(() => {
    getListWarehouseProducts(currentPage);
    !warehouses?.length && getListWarehouses();
  }, [currentPage, warehouseId]);

  const getListWarehouses = () => {
    // 调用 listSuppliers API，并处理响应
    listWarehouses({
      page: 1,
      size: 300,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      setWarehouses(res.data?.warehouses || []);
    });
  };

  const handleTagClick = () => {
    setModalVisible(true);
  };

  const handleModalClose = () => {
    setModalVisible(false);
  };

  useEffect(() => {
    getReminderCount();
  }, []);

  const getReminderCount = () => {
    // 调用 listWarehouseProducts API，并处理响应
    listWarehouseProducts({
      page: 1,
      size: 300,
    }).then((res: any) => {
      if (res?.code !== 0) {
        message.error(res.msg);
        return;
      }
      const { warehouse_products, total } = res.data;
      console.log("warehouse_products", warehouse_products);
      let _count = 0;
      let arr: string[] = [];
      warehouse_products.forEach((el: any) => {
        const { product_name, warehouse_name } = el;
        if (el?.remind) {
          let _hintText = `${warehouse_name}-${product_name}`;
          arr.push(_hintText);
          _count += 1;
        }
      });
      setHintText(arr.join("/"));
      console.log("_count", _count);
      setCount(_count);
      setModalVisible(!!_count);
    });
  };

  return (
    <div>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
        }}
      >
        <Select
          placeholder="请选择仓库"
          allowClear
          onChange={(value: number) => {
            setWarehouseId(value);
          }}
          style={{
            width: 200,
          }}
        >
          {warehouses.map((ele) => (
            <Option key={ele.id} value={ele.id}>
              {ele.warehouse_name}
            </Option>
          ))}
        </Select>
        <Button
          style={{ marginTop: "7px", marginLeft: "10px", float: "right" }}
          onClick={() => {
            setCurrentWarehouseProduct(null);
            setIsWarehouseProductModalVisible(true);
          }}
          size="large"
          type="primary"
        >
          添加仓库物品
        </Button>
      </div>

      <Table
        dataSource={warehouseProductList}
        columns={columns}
        rowKey="id"
        pagination={{
          pageSize,
          defaultCurrent: 1,
          onChange: setCurrentPage,
          total: totalWarehouseProducts,
        }}
      />
      <WarehouseProductModal
        warehouses={warehouses}
        title={currentWarehouseProduct ? "编辑仓库物品" : "添加仓库物品"}
        visible={isWarehouseProductModalVisible}
        onCancel={() => {
          setIsWarehouseProductModalVisible(false);
        }}
        onOk={handleWarehouseProductModalOk}
        defaultValue={currentWarehouseProduct || {}}
      />

      <Modal
        visible={modalVisible}
        title="仓库物品阈值提醒"
        onCancel={handleModalClose}
        footer={null}
      >
        <RemindTag remind={!!count} text={"仓库物品阈值标识"} />
        <div>{hintText}</div>
      </Modal>
    </div>
  );
};

export default ListWarehouseProducts;
